package com.wu.controller.restful;

import com.alibaba.fastjson.JSON;
import com.wu.common.ResponseData;
import com.wu.entity.ShiroUser;
import com.wu.service.impl.UserService;
import com.wu.util.EncryptUtil;
import com.wu.util.JwtUtil;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author wuyanshen
 * @date 2019-01-14 9:23 PM
 * @discription 描述
 */
@RestController
@RequestMapping("/restful/user")
public class UserRestController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "api/getUser", method = RequestMethod.GET)
    public ResponseData user() {
        ResponseData responseData = new ResponseData();
        ShiroUser user = new ShiroUser();
        user.setId("1");
        user = userService.get(user);

        responseData.setCode(200);
        responseData.setMsg("获取用户成功");
        responseData.setData(user);
        return responseData;
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResponseData login(@RequestBody Map map) {
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        ShiroUser userBean = userService.getUserByLoginName(username);
        //将页面传来的password进行MD5加密
        String pagePwd = EncryptUtil.encrypt(username, password, "MD5");
        if (userBean.getPassword().equals(pagePwd)) {

            ShiroUser user = new ShiroUser();
            user.setId(userBean.getId());
            user.setLoginName(username);
            user.setPassword(pagePwd);
            String subject = JSON.toJSONString(user);
            String token = JwtUtil.issueJWT(userBean.getId(), subject, "admin",null,null, SignatureAlgorithm.HS256);

            System.out.println("生成的token= "+token);
            return new ResponseData(200, "登录成功", token);
        } else {
            throw new UnauthorizedException();
        }
    }

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public ResponseData test() {
        ResponseData responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMsg("测试成功");
        responseData.setData("");
        return responseData;
    }
}
